package org.csu.mypetstore.Controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.LineItem;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    LogService logService;
    @Autowired
    CartService cartService;
    @Autowired
    AccountService accountService;
    @Autowired
    CategortService categortService;


    @RequestMapping("/ViewMyOrder")
    public String ViewMyOrderServlet(Account account) {
        String username = account.getUsername();
        if (username == null) {
            return "/account/SignonForm";
        } else {
            return "/order/ViewOrder";
        }
    }

    @RequestMapping("/ViewListOrder")
    public String ViewListOrder(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        if(account == null){
            return "/account/SignonForm";
        }
        String username = account.getUsername();
        List<Order> orderList = orderService.getOrdersByUsername(username);
        model.addAttribute("orderList", orderList);
        session.setAttribute("orderList", orderList);
        if (account.getUsername() != null) {
            String logInfo = " 查看订单 ";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        return "/order/ListOrder";
    }

    @RequestMapping("/NewOrderForm")
    public String NewOrderForm(HttpServletRequest request, Cart cart, Model model) {
        HttpSession session = request.getSession();
        List<Cart> cartList = (List<Cart>) session.getAttribute("cartList");
        Account account = (Account) session.getAttribute("account");
        account = accountService.getAccount(account.getUsername());
        if (account == null) {
            model.addAttribute("message", "You must sign on before attempting to check out.  Please sign on and try checking out again.");
            return "/account/SignonForm";
        } else if (cart != null) {
            Order order = new Order();
            order.initOrder(account, cart);
            model.addAttribute("order", order);
            model.addAttribute("orderId",order.getOrderId());
            if (account != null) {
                String logInfo = " 跳转到新订单页面";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }
            model.addAttribute("cartList", cartList);
            session.setAttribute("order",order);
            return "/order/together";

        } else {
            model.addAttribute("message", "An order could not be created because a cart could not be found.");
            if (account != null) {
                String logInfo = " 生成订单页面信息错误";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }
            return "/common/Error";
        }
    }

    @RequestMapping("/ViewOrder")
    public String ViewOrder(HttpServletRequest request, Model model) {
        Order order;
        Cart cart;
        String orderId = null;
        String username = null;
        BigDecimal subtoatl = new BigDecimal(0);
        BigDecimal total = new BigDecimal(0.0);
        List<Cart> cartList;
        HttpSession session = request.getSession();
        orderId = request.getParameter("orderId");
        Account account = (Account) session.getAttribute("account");
        username = account.getUsername();
        cartList = (List<Cart>) session.getAttribute("cartList");
        if (cartList != null) {
            subtoatl = new BigDecimal(0);
            int k = 0;
            while (k < cartList.size()) {
                subtoatl = subtoatl.add(cartList.get(k).getTotal());
                k++;
            }
        }
        model.addAttribute("total", subtoatl);
        if (account != null) {
            String logInfo = " 查看订单 ";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }

        if (orderId != null) {
            order = orderService.getOrder(Integer.valueOf(orderId));
        } else {
            order = (Order) session.getAttribute("order");
            order.setTotalPrice(subtoatl);
            ArrayList<LineItem> lineItemIterator = new ArrayList<LineItem>();
            for (int i = 0; i < cartList.size(); i++) {
                LineItem lineItem = new LineItem();
                lineItem.setUnitPrice(cartList.get(i).getListprice());
                lineItem.setQuantity(cartList.get(i).getQuantity());
                lineItem.setItemId(cartList.get(i).getItemid());
                lineItem.setItem(categortService.getItem(cartList.get(i).getItemid()));
                lineItem.setLineNumber(i + 1);
                // lineItem.setOrderId(id);
                lineItemIterator.add(lineItem);
            }
            order.setLineItems(lineItemIterator);
        }
        if (order != null) {
            orderService.insertOrder(order);
            model.addAttribute("order", order);
            //清空购物车
            cartService.deletecart_by_username(username);
            cart = null;
            model.addAttribute("cart", cart);

            model.addAttribute("message", "Thank you, your order has been submitted.");
            return "order/ViewOrder";
        } else {
            model.addAttribute("message", "An error occurred processing your order (order was null).");
            return "/common/Error";
        }
    }

    @RequestMapping("/ViewmyOrder")
    public String ViewmyOrder(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        List<Order> orders = orderService.getOrdersByUsername(account.getUsername());
        session.setAttribute("order", orders);
        model.addAttribute("order", orders);
        return "/order/ViewOrder";

    }

    @RequestMapping("/ConfirmOrderForm")
    public String ConfirmOrderForm(HttpServletRequest request, Model model){
        Order order;
        HttpSession session = request.getSession();
        order = (Order) session.getAttribute("order");
        Account account = (Account) session.getAttribute("account");
            if (account != null) {
                String logInfo = logService.logInfo(" ") + " 确认生成订单 ";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }//对order赋值
            String cardType = request.getParameter("cardType");
            String creditCard = request.getParameter("creditCard");
            String expiryDate = request.getParameter("expiryDate");
            String billToFirstName = request.getParameter("billToFirstName");
            String billToLastName = request.getParameter("billToLastName");
            String billAddress1 = request.getParameter("billAddress1");
            String billAddress2 = request.getParameter("billAddress2");
            String billCity = request.getParameter("billCity");
            String billState = request.getParameter("billState");
            String billZip = request.getParameter("billZip");
            String billCountry = request.getParameter("billCountry");
            if (cardType != null) {
                order.setCardType(cardType);
            }
            if (creditCard != null) {
                order.setCreditCard(creditCard);
            }
            if (expiryDate != null) {
                order.setExpiryDate(expiryDate);
            }

            if (billToFirstName != null) {
                order.setBillToFirstName(billToFirstName);
            }
            if (billToLastName != null) {
                order.setBillToLastName(billToLastName);
            }
            if (billAddress1 != null) {
                order.setBillAddress1(billAddress1);
            }
            if (billAddress2 != null) {
                order.setBillAddress2(billAddress2);
            }
            if (billCity != null) {
                order.setBillCity(billCity);
            }
            if (billState != null) {
                order.setBillState(billState);
            }
            if (billZip != null) {
                order.setBillZip(billZip);
            }
            if (billCountry != null) {
                order.setBillCountry(billCountry);
            }
            session.setAttribute("order", order);
            model.addAttribute("order",order);
            return "/order/ConfirmOrder";


    }


}
